<template>
  <div class="profile-container">
    <el-card>
      <h2>个人设置</h2>
      
      <!-- 未登录状态显示 -->
      <div v-if="!authStore.isLoggedIn" class="unlogin-state">
        <el-empty 
          description="请先登录以查看和修改个人信息"
          class="empty-state"
        >
          <el-button type="primary" @click="goToLogin">
            前往登录
          </el-button>
        </el-empty>
      </div>
      
      <!-- 已登录状态内容 -->
      <div v-else>
        <el-tabs v-model="activeTab" class="setting-tabs">
          <!-- 基本信息修改 -->
          <el-tab-pane label="基本信息" name="info">
            <el-form 
              :model="profileInfo" 
              ref="profileFormRef" 
              :rules="profileRules" 
              label-width="120px"
              class="profile-form"
            >
              <el-form-item label="头像" class="avatar-upload">
                <el-upload
                  class="avatar-uploader"
                  action="#"
                  :show-file-list="false"
                  :http-request="handleAvatarUpload"
                  :before-upload="beforeAvatarUpload"
                  :on-error="handleUploadError"
                  :on-success="handleUploadSuccess"
                  :disabled="isUploading || loading"
                >
                  <div class="avatar-container">
                    <img 
                      v-if="profileInfo.avatarUrl" 
                      :src="profileInfo.avatarUrl" 
                      class="avatar-image" 
                      :alt="`${profileInfo.username || profileInfo.username}的头像`"
                      @load="handleImageLoad"
                      @error="handleImageError"
                    />
                    <div v-else class="avatar-placeholder">
                      <el-icon v-if="!isUploading"><Plus /></el-icon>
                      <el-icon v-else><Loading /></el-icon>
                      <span class="upload-text">上传头像</span>
                    </div>
                  </div>
                </el-upload>
                <div class="upload-tip">支持JPG、PNG格式,不超过2MB</div>
                <el-alert 
                  v-if="uploadError" 
                  :title="uploadError" 
                  type="error" 
                  show-icon 
                  class="upload-error-alert"
                  :closable="true"
                  @close="uploadError = ''"
                />
              </el-form-item>

              <el-form-item label="用户名" prop="username">
                <el-input v-model="profileInfo.username" />
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="profileInfo.email" type="email" />
                <div class="format-hint">请输入有效的邮箱地址（例如：example@domain.com）</div>
              </el-form-item>
              <el-form-item label="电话" prop="phone">
                <el-input v-model="profileInfo.phone" />
                <div class="format-hint">请输入11位有效的手机号码（例如：13800138000）</div>
              </el-form-item>
            </el-form>
          </el-tab-pane>

          <!-- 密码修改 -->
          <el-tab-pane label="密码修改" name="password">
            <el-form 
              :model="passwordForm" 
              ref="passwordFormRef" 
              :rules="passwordRules" 
              label-width="120px"
              class="profile-form"
            >
              <el-form-item label="原密码" prop="oldPassword">
                <el-input v-model="passwordForm.oldPassword" type="password" show-password />
              </el-form-item>
              <el-form-item label="新密码" prop="newPassword">
                <el-input v-model="passwordForm.newPassword" type="password" show-password />
                <div class="format-hint">密码长度需在6-20个字符之间</div>
              </el-form-item>
              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
                <div class="format-hint">请再次输入相同的新密码</div>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
        
        <div class="form-actions">
          <el-button type="primary" @click="handleSaveProfile" :loading="loading">保存修改</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { Plus, Loading } from '@element-plus/icons-vue'
import { ElMessage, ElNotification } from 'element-plus'
import { userAPI } from '../../api/user'

// 状态管理与路由
const authStore = useAuthStore()
const router = useRouter()

// 关键修复：在组件初始化最开始就执行认证初始化
authStore.initAuth()

// 表单数据
const profileInfo = reactive({
  username: '',
  email: '',
  phone: '',
  avatarUrl: '',
  avatarFile: null  // 新增：保存头像文件对象
})

const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单引用
const profileFormRef = ref(null)
const passwordFormRef = ref(null)

// 状态
const activeTab = ref('info')
const isUploading = ref(false)  // 上传状态标记
const loading = ref(false)      // 整体加载状态
const uploadError = ref('')     // 头像上传错误信息

// 更新用户信息
const updateUserInfo =async () => {
  if (authStore.isLoggedIn && authStore.user) {
    Object.assign(profileInfo, authStore.user)
    // 确保头像文件初始为空
    profileInfo.avatarFile = null    
    let user =await userAPI.getUserByName(authStore.user.Username)    
    profileInfo.phone = user.data[0].phone
  } else {
    // 清空表单
    Object.keys(profileInfo).forEach(key => {
      profileInfo[key] = ''
    })
    profileInfo.avatarFile = null
  }
}

// 监听登录状态变化
watch(() => authStore.user, () => {
  updateUserInfo()
}, { immediate: true, deep: true })

// 监听store中的用户数据变化
watch(() => authStore.user, (newUser) => {
  if (newUser) {
    profileInfo.username = newUser.Username || ''
    profileInfo.email = newUser.Email || ''
    profileInfo.phone = newUser.Phone || ''
    profileInfo.avatarUrl = newUser.avatar || ''
  }  
}, { immediate: true })

// 表单验证规则
const profileRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在2-20个字符之间', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入11位有效的手机号码', trigger: 'blur' }
  ]
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6-20个字符之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 保存个人设置
const handleSaveProfile = async () => {
  loading.value = true
  uploadError.value = ''
  let user =await userAPI.getUserByName(profileInfo.username)
  
  try {
    if (activeTab.value === 'info') {
      await profileFormRef.value.validate()
      
      // 创建FormData对象，用于同时提交表单数据和头像文件  = new FormData()
      const formData ={
        username:profileInfo.username,
        email:profileInfo.email,
        phone:profileInfo.phone,
        password:user.data[0].password,
        roleId:user.data[0].roleId,
      }      
      // 更新用户信息（包括可能的头像）
      await userAPI.updateUser(user.data[0].id,formData)
      
      ElNotification({
        title: '成功',
        message: '个人信息更新成功',
        type: 'success'
      })
    } else {
      await passwordFormRef.value.validate()
      
      // 验证原密码
      const users = JSON.parse(localStorage.getItem('registeredUsers') || '{}')
      const currentUser = users[authStore.user.username]
      
      if (!currentUser || currentUser.password !== passwordForm.oldPassword) {
        throw new Error('原密码不正确')
      }
      
      // 更新密码
      await authStore.updateUser({
        username: authStore.user.username,
        password: passwordForm.newPassword
      })
      
      ElNotification({
        title: '成功',
        message: '密码修改成功，请重新登录',
        type: 'success'
      })
      
      // 密码修改后退出登录
      setTimeout(() => {
        authStore.logout()
        router.push('/login')
      }, 1000)
    }
  } catch (error) {
    console.error('保存失败:', error)
    if (error.name !== 'ValidationError') {
      ElMessage.error(error.message || '保存失败，请重试')
    }
  } finally {
    loading.value = false
  }
}

// 上传前验证（与注册界面一致）
const beforeAvatarUpload = (file) => {
  uploadError.value = ''  // 重置上传错误
  
  // 验证文件类型
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    uploadError.value = '请上传JPG或PNG格式的图片'
    return false
  }
  
  // 验证文件大小
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    uploadError.value = '图片大小不能超过2MB'
    return false
  }
  
  // 生成临时预览URL（本地预览，不上传服务器）
  const reader = new FileReader()
  reader.onload = (e) => {
    profileInfo.avatarUrl = e.target.result  // 设置预览图
  }
  reader.readAsDataURL(file)
  
  profileInfo.avatarFile = file  // 保存文件对象，更新信息时一并提交
  isUploading.value = true
  
  return true
}

// 处理头像上传（仅客户端预览，实际更新时提交）
const handleAvatarUpload = async (options) => {
  try {
    // 模拟上传过程，实际项目中可根据需求调整
    setTimeout(() => {
      options.onSuccess({ status: 'success' })
      isUploading.value = false
    }, 300)
  } catch (error) {
    options.onError(error)
    isUploading.value = false
  }
}

// 图片加载完成后调整显示（与注册界面一致）
const handleImageLoad = (e) => {
  const img = e.target;
  const container = img.parentElement;
  
  // 根据图片和容器尺寸自动调整显示方式
  if (img.naturalWidth > container.clientWidth || img.naturalHeight > container.clientHeight) {
    // 图片大于容器，裁剪显示
    img.style.objectFit = 'cover';
  } else {
    // 图片小于容器，完整显示
    img.style.objectFit = 'contain';
  }
};

// 上传成功处理
const handleUploadSuccess = () => {
  ElMessage.success('头像已加载成功')
}

// 上传错误处理
const handleUploadError = (error) => {
  uploadError.value = '头像处理失败: ' + (error.message || '请重试')
  console.error('头像处理错误:', error)
  isUploading.value = false
}

// 处理图片加载失败
const handleImageError = () => {
  uploadError.value = '头像加载失败，请重新上传'
  console.error('头像加载失败，URL:', profileInfo.avatarUrl)
}

// 前往登录页
const goToLogin = () => {
  router.push({
    path: '/',
    query: { redirect: router.currentRoute.value.fullPath }
  })
}

// 初始化
onMounted(async () => {
  await nextTick()
  authStore.initAuth()
  updateUserInfo()
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.setting-tabs {
  margin-top: 20px;
}

.profile-form {
  margin-top: 20px;
}

.form-actions {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 未登录状态样式 */
.unlogin-state {
  padding: 50px 20px;
  text-align: center;
  min-height: 300px;
}

.empty-state {
  max-width: 300px;
  margin: 0 auto;
}

/* 头像上传样式 - 与注册界面保持一致 */
.avatar-upload {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
  margin-bottom: 15px;
}

/* 头像容器 - 固定尺寸圆形 */
.avatar-container {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  overflow: hidden;
  position: relative;
  border: 1px dashed #ccc;
  background-color: #f9f9f9;
  transition: all 0.3s ease;
  cursor: pointer;
}

/* 头像图片 - 自适应容器 */
.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 核心属性：保持比例填充容器 */
  transition: all 0.3s ease;
}

/* 上传占位样式 */
.avatar-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #8c939d;
}

.upload-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.upload-text {
  font-size: 14px;
}

/* 上传提示样式 */
.upload-tip {
  font-size: 12px;
  color: #666;
  margin-top: 8px;
  width: calc(100% - 120px - 16px);
}

.upload-error-alert {
  margin-top: 10px;
  padding: 6px 12px;
  font-size: 13px;
  width: 100%;
}

/* 格式提示 */
.format-hint {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
  line-height: 1.5;
}

.el-form-item {
  margin-bottom: 25px;
}

/* 悬停效果 */
.avatar-container:hover {
  border-color: #409EFF;
  background-color: rgba(64, 158, 255, 0.05);
}

/* 响应式调整 */
@media (max-width: 480px) {
  .avatar-upload {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .upload-tip {
    width: 100%;
  }
}
</style>
    